<template>
  <div class="page">
    <Navbar  title="我的订单"/>
    <view class="order-container">
      <!-- 顶部搜索栏 -->
      <view class="search-bar">
        <view class="search-input">
          <u-icon name="search" size="32" color="#999"></u-icon>
          <input
              type="text"
              v-model="searchKeyword"
              placeholder="搜索地址/充电站"
              @confirm="handleSearch"
          />
        </view>
      </view>

      <!-- 订单状态切换 -->
      <view class="order-tabs">
        <view
            v-for="tab in tabs"
            :key="tab.value"
            class="tab-item"
            :class="{ active: currentTab === tab.value }"
            @click="switchTab(tab.value)"
        >
          {{ tab.label }}
        </view>
      </view>

      <!-- 订单列表 -->
      <div style="flex-grow: 1;overflow:hidden;">
        <scroll-view
            class="order-list"
            scroll-y
            enable-back-to-top
            refresher-enabled
            :refresher-triggered="isRefreshing"
            @refresherrefresh="onRefresh"
            @scrolltolower="onScroll"
            :style="{ height: '100%' }"
        >
          <view
              v-for="(item,index) in orderList"
              :key="item.id"
              class="order-item"
          >
            <view class="order-header">
              <text class="time">{{ formatterTime(item.createTime) }}</text>
              <text :class="['status', item.chargeStatus]">{{ getStatusText(item.chargeStatus) }}</text>
            </view>
            <view class="station-name">
              {{ item.plotName }}
            </view>
            <view class="charging-info">
              <view class="info-item">
                <view class="dot" :class="item.chargeStatus"></view>
                <text class="label">充电时长：</text>
                <text class="value">{{ formateTime(item.chargedTime) }}</text>
              </view>
              <view class="info-item">
                <view class="dot" :class="item.chargeStatus"></view>
                <text class="label">充电度数：</text>
                <text class="value">{{ item.chargedElectricity || 0 }}度</text>
              </view>
            </view>
            <view class="fee-info">
              <view class="dot" :class="item.chargeStatus"></view>
              <text class="label">费用：</text>
              <text class="value">{{ item.chargeMoney || 0 }}元</text>
            </view>
            <view class="order-footer">
              <view class="btn-group">
                <view v-if="item.chargeStatus === 'CHARGING'" class="btn comment-btn" @click.stop="addCharging(index)">
                  续充
                </view>
                <!--                <view v-if="order.chargeStatus === 'CHARGING_COMPLETE' && !order.hasComment" class="btn comment-btn" @click.stop="goToComment(order.id)">-->
                <!--                  评价-->
                <!--                </view>-->
                <view class="btn detail-btn" @click="goToDetail(index)">
                  详情
                </view>
                <view v-if="item.chargeStatus === 'CHARGING'" class="btn stop-btn" @click.stop="stopCharging(index)">
                  停止充电
                </view>
              </view>
            </view>
          </view>

          <u-loadmore v-if="orderList.length" :status="loading" />
          <div style="height: 40px"></div>
          <u-empty  v-if="orderList.length === 0" mode="order"></u-empty>
        </scroll-view>
        <Tabbar/>
      </div>
    </view>
  </div>
</template>
<script>
import Tabbar from "../../components/Tabbar.vue";
import Page from "../../components/Page.vue";
import dayjs from "dayjs";
import Navbar from "../../components/navbar.vue";

export default {
  components: {Navbar, Tabbar,Page},
  data() {
    return {
      isRefreshing: false,
      searchKeyword: '',
      currentTab: '',
      tabs: [
        { label: '全部', value: '' },
        { label: '充电中', value: 'CHARGING' },
        { label: '已完成', value: 'CHARGING_COMPLETE' }
      ],
      loading: 'loadmore',
      pageNo: 1,
      pageSize: 6,
      total: 0,
      orderList: []
    }
  },
  onLoad() {
    this.getList(true)
  },
  onShow() {
    // 如果需要每次显示页面都刷新，可以取消注释下面这行
    // this.getList(true)
  },
  methods: {
    // 获取订单列表
    async getList(reset = false) {
      if (reset) {
        this.pageNo = 1
        this.orderList = []
      } else {
        if (this.loading === 'nomore') return
      }
      this.loading = 'loading'
      try {
        uni.showLoading({
          title: '加载中...'
        })

        const mockData = await this.$api.getOrderPage({
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          name: this.searchKeyword,
          chargeStatus: this.currentTab
        })
        const { list, total } = mockData
        this.total = total

        if (reset) {
          this.orderList = list
        } else {
          this.orderList = [...this.orderList, ...list]
        }

        this.pageNo++
        this.loading = this.orderList.length >= total ? 'nomore' : 'loadmore'
      } catch (e) {
        console.log(e)
        this.loading = 'loadmore'
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    formatterTime(date) {
      if (!date) return date
      return dayjs(date).format('YYYY-MM-DD mm:hh:ss')
    },
    // 下拉刷新
    async onRefresh() {
      if (this.isRefreshing) return
      this.isRefreshing = true
      try {
        await this.getList(true)
      } catch (e) {
      } finally {
        this.isRefreshing = false
      }
    },

    // 上拉加载更多
    onScroll() {
      if (this.loading === 'loading') return
      this.getList()
    },

    // 搜索
    handleSearch() {
      this.getList(true)
    },

    // 切换标签
    switchTab(tab) {
      if (this.currentTab === tab) return
      this.currentTab = tab
      this.getList(true)
    },

    // 跳转到订单详情
    goToDetail(index) {
      try {
        const item = this.orderList[index]
        console.log(index,item)
        const urlMap = {
          'NOT_CHARGING': '/pages/order/charging',
          'CHARGING': '/pages/order/charging',
          'CHARGING_COMPLETE': '/pages/order/completed'
        }
        const url = urlMap[item.chargeStatus]
        if (!url || !item.orderId) return
        uni.navigateTo({ url: `${url}?id=${item.orderId}` })
      } catch (e) {
        console.log(e)
      }
    },
    addCharging(index) {
      const item = this.orderList[index]
      console.log(index,item)
      uni.navigateTo({ url: `/pages/charging/add?id=${item.orderId}&portId=${item.portId}&stationId=${item.stationId}&orderType=${item.orderType}` })
    },
    // 停止充电
    stopCharging(index) {
      const item = this.orderList[index]
      console.log(index,item)
      uni.showModal({
        title: '提示',
        content: '确定要停止充电吗？',
        success: (res) => {
          if (res.confirm) {
            // TODO: 调用停止充电接口
            this.$api.closeOrder({
              id: item.orderId
            }).then(() => {
              uni.showToast({
                title: '已结束充电',
                icon: 'success',
                success: () => {
                  setTimeout(() => {
                    uni.navigateTo({
                      url: '/pages/order/completed?id=' + item.orderId
                    })
                  }, 500)
                }
              })
            })
          }
        }
      })
    },

    // 跳转到评论页面
    goToComment(orderId) {
      uni.navigateTo({
        url: `/pages/order/comment?id=${orderId}`
      })
    },

    // 获取订单状态文本
    getStatusText(status) {
      const statusMap = {
        'NOT_CHARGING': '待充电',
        'CHARGING': '充电中',
        'START_FAIL': '充电失败',
        'CHARGING_COMPLETE': '已完成'
      }
      return statusMap[status] || status
    },
    formateTime(minutes) {
      if (!minutes) return 0
      if (minutes < 60) {
        return  minutes + '分钟'
      }

      var hours = Math.floor(minutes / 60);
      var remainingMinutes = minutes % 60;
      return hours + "时" + remainingMinutes + "分";
    },
  }
}
</script>

<style lang="scss" scoped>
.order-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #F5F5F5;
  overflow: hidden;
}

.search-bar {
  padding: 20rpx 30rpx;
  background: #fff;

  .search-input {
    display: flex;
    align-items: center;
    background: #F5F5F5;
    padding: 16rpx 24rpx;
    border-radius: 32rpx;

    input {
      flex: 1;
      margin-left: 16rpx;
      font-size: 28rpx;
    }
  }
}

.order-tabs {
  display: flex;
  background: #fff;
  padding: 0 30rpx;
  margin-bottom: 20rpx;

  .tab-item {
    position: relative;
    padding: 20rpx 0;
    margin-right: 48rpx;
    font-size: 28rpx;
    color: #666;

    &.active {
      color: #333;
      font-weight: 500;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 48rpx;
        height: 4rpx;
        background: #1296db;
        border-radius: 2rpx;
      }
    }
  }
}

.order-list {
  background: #F5F5F5;
  box-sizing: border-box;
  height: 100%;
  :deep(.uni-scroll-view-refresh) {
    background: #f5f5f5;
  }
}

.order-item {
  padding: 30rpx;
  background: #fff;
  border-radius: 16rpx;
  margin: 0 30rpx;
  margin-bottom: 20rpx;
  .order-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;

    .time {
      font-size: 24rpx;
      color: #999;
    }

    .status {
      font-size: 24rpx;

      &.NOT_CHARGING,
      &.CHARGING{
        color: #1296db;
      }

      &.CHARGING_COMPLETE {
        color: #1296db;
      }
      &.START_FAIL {
        color: red;
      }
    }
  }

  .station-name {
    font-size: 32rpx;
    font-weight: 500;
    margin-bottom: 20rpx;
  }

  .charging-info {
    margin-bottom: 16rpx;
  }

  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 12rpx;

    .dot {
      width: 8rpx;
      height: 8rpx;
      border-radius: 50%;
      margin-right: 12rpx;

      &.NOT_CHARGING,
      &.CHARGING{
        background-color: #1296db;
      }

      &.CHARGING_COMPLETE {
        background-color: #1296db;
      }
      &.START_FAIL {
        background-color: red;
      }
    }

    .label {
      font-size: 28rpx;
      color: #666;
    }

    .value {
      font-size: 28rpx;
      color: #333;
    }
  }

  .fee-info {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;

    .dot {
      width: 8rpx;
      height: 8rpx;
      border-radius: 50%;
      margin-right: 12rpx;

      &.NOT_CHARGING,
      &.CHARGING{
        background-color: #1296db;
      }

      &.CHARGING_COMPLETE {
        background-color: #1296db;
      }
      &.START_FAIL {
        background-color: red;
      }
    }

    .label {
      font-size: 28rpx;
      color: #666;
    }

    .value {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }
  }

  .order-footer {
    display: flex;
    justify-content: flex-end;

    .btn-group {
      display: flex;
      gap: 20rpx;
    }

    .btn {
      padding: 12rpx 32rpx;
      font-size: 28rpx;
      border-radius: 32rpx;

      &.stop-btn {
        color: #fff;
        background: #FF4D4F;
      }

      &.comment-btn {
        color: #1296db;
        background: rgba(4, 200, 174, 0.1);
      }

      &.detail-btn {
        color: #666;
        background: #F5F5F5;
      }
    }
  }
}
</style>
